package server

import (
	"log"
	"my-gameserver-go/core/eventbus"
	"my-gameserver-go/core/mynet/conn"
	"my-gameserver-go/core/mynet/handler/abs"
	"my-gameserver-go/logic/consts"
	enums_ctxstate "my-gameserver-go/logic/consts/enums"
	player_mananger "my-gameserver-go/logic/player/manager"
	"strconv"
	"time"
)

func init() {
	listener := new(ConnListener)
	eventbus.Subscribe(consts.CONN_ACTIVE, listener.ConnActive)
	eventbus.Subscribe(consts.CONN_ACTIVE, listener.ConnClose)

}

type ConnListener struct {
}

func (l ConnListener) ConnActive(c *conn.GameConnection) {
	//设置玩家连接建立状态
	c.SetAttr(consts.ConnPlayerState, enums_ctxstate.CONNECT)
	c.SetAttr(consts.Connect_Time, time.Now().Second())
	log.Println(consts.LOG_LOGIN_PREFIX + "connActive." + c.LogInfo())
}
func (l ConnListener) ConnClose(c *conn.GameConnection) {
	beginTime := c.Attr(consts.Connect_Time)
	if beginTime == nil {
		beginTime = time.Now().Second()
	}
	onlineTime := time.Now().Second() - beginTime.(int)
	log.Println(consts.LOG_LOGIN_PREFIX + "conn disconnected." + c.LogInfo() + strconv.Itoa(onlineTime))
	channelInfo := c.Attr(consts.ChannelInfo)
	if channelInfo != nil {
		//连接断开
		player, ok := player_mananger.InsPlayerManager.GetPlayerByConn(c.Conn)
		connState := c.Attr(consts.ConnPlayerState)
		if connState == enums_ctxstate.NORMAL {
			if ok {
				if player.Conn == c {
					log.Println(consts.LOG_LOGIN_PREFIX + "conn disconnected,player begin login out" + c.LogInfo() + strconv.Itoa(onlineTime))
					c.SetAttr(consts.ConnPlayerState, enums_ctxstate.CHANNEL_INACTIVE)
					//玩家goroutine执行
					player_mananger.InsPlayerManager.InnerHandlerSend(player.RoutineChanIndex, abs.NewInnerHandler(func() {
						player_mananger.InsPlayerManager.PlayerOut(player)
					}))
				} else {
					log.Println(consts.LOG_LOGIN_PREFIX + "conn disconnected. ctx is not equals  :" + c.LogInfo())
				}
			} else {
				log.Println(consts.LOG_LOGIN_PREFIX + "conn state normal but player is nil :" + c.LogInfo())
			}
		} else {
			log.Println(consts.LOG_LOGIN_PREFIX + "conn state exception connState:" + connState.(string) + c.LogInfo())
		}
	} else {
		//顶号
		log.Println(consts.LOG_LOGIN_PREFIX + "conn OFF_SITE_LANDING!" + c.LogInfo() + strconv.Itoa(onlineTime))
	}
}
